package serialComm;
import javax.comm.*;
import java.io.*;
import java.util.*;

public class SerialSms implements Runnable{
	private static final String PORTNAME = "COM4";
	protected static final int LONGDELAY = 5000;
	protected static final int SHORTDELAY = 1000;
	protected static final int MEDIUMDELAY = 3000; 
//	private static final int TIMEOUTSECS = 20;
	protected static final int BAUD = 115200;
	private static final int SERIAL = 1;
	private static final int MAX_CHARS = 162;
	private static InputStream is;
	private static PrintStream os;
	
	private static final char ctrlZ=(char)26;
	
	private boolean debug = false;
	static String response;
	private static CommPortIdentifier cpi;
	private CommPort cp;
	private static SerialPort myPort;
	
	ResponseText responseText;
	/**
	 * @param args
	 */
	String pName;
	Integer pType;
	public SerialSms() {
		//d = new BufferedReader(new InputStreamReader(is));
	}
	public void getAllPorts() throws UnsupportedCommOperationException, IOException, InterruptedException {
		
		Enumeration pList = CommPortIdentifier.getPortIdentifiers();
	
		System.err.println("Detectecting Ports ...");
		while(pList.hasMoreElements()) {
			cpi = (CommPortIdentifier)pList.nextElement();
			
			pName = cpi.getName();			
			pType = cpi.getPortType();
			if(debug) {
				System.out.println("Port Name : "+pName);
				System.out.println("Port Type : "+pType);
				System.out.println();
			}
			
			if(pName.equals(PORTNAME) && pType == SERIAL) 
				try {
					
					System.out.print("Using Port : " +pName);
					System.out.println();
					cp = cpi.open("Sms Banking System",SHORTDELAY);
					myPort = (SerialPort) cp;
					myPort.setSerialPortParams(BAUD, SerialPort.DATABITS_8,SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
				}catch (PortInUseException p) {
					System.err.println("Port in Use By Other Programs.");
					System.exit(0);
				}	
		}
	}
	
	public void run() {
		
	}
	
	
	protected synchronized void sendCommand(String s) throws IOException, InterruptedException {

        if (debug) {
            System.out.print(">>> ");
            System.out.print(s);
            System.out.println();
        }
        try {
        	os = new PrintStream(myPort.getOutputStream(),true);
            os.print(s);			// Actually sends the command to modem
            os.print("\r\n");		// Acts like as if we hit the enter key
              
            
        	is = myPort.getInputStream( );  
        	System.err.println("(Wait) Buffering InputStream ... ");
        	Thread.sleep(LONGDELAY);
            byte[] readBuffer =  new byte[MAX_CHARS];
           
            	int numbytes =is.read(readBuffer);
            
            response = new String(readBuffer);
            if(debug) {
            	responseText = new ResponseText();
            	//a.set();
//	            System.err.print("Response  : "+responseText.response);
	            if(responseText.response.indexOf("REC READ")>0) {
	            	System.out.println();
	            	System.out.println("Return Code : " + responseText.getReturnCode());
	            	System.out.println("Action : " + responseText.getAction());
	            	System.out.println("Number : " + responseText.getNumber());
	            	System.out.println("Date : " + responseText.getDate());
	            	System.out.println("Time : " + responseText.getTime());
	            	System.out.println("Text : " + responseText.getActualData());
	            }
            }
            else {
            	
            	String res = responseText.response;
//            	+CMGR: "REC READ","+9779841778373",,"09/03/17,17:52:39+20"
            	System.out.println();
            	System.err.println("Extracted Text : " + res);
            	
            }
            
            // Expect the modem to echo the command.

            if (!expect(s)) {
                System.err.println("WARNING: Modem did not echo command.");
            }

        }catch(IOException e) {
        	System.err.print(e.toString());
        }
        
    }

	//	
    /** Read a line, saving it in "response". 
     * @return true if the expected String is contained in the response, false if not.

     */

	protected boolean expect(String exp) throws IOException {
        if (debug) {
            System.out.print("<<< ");
            System.out.print(response);
            System.out.println( );
            
        }

        return response.indexOf(exp) >= 0;
    }
	
	protected synchronized void sendMsg() throws InterruptedException, IOException {
		try {
//			responseText = new ResponseText();
			String number = "+9779848027757";
//			number = responseText.getNumber();
			String setTextMode = new String("AT+CMGF=1");
			String setNumber = new String("AT+CMGS=\"" + number + "\"");
			if(debug) {
				System.err.print("Send Message to Number : "+setNumber);
//				System.out.println("<<<"+command);				
			}
			
			sendCommand(setTextMode);
			Thread.sleep( SHORTDELAY / 2 );
			
			Boolean checkState = parseMsg("OK");
			if(checkState) {
				
				if(debug) System.out.println("OK is Returned");
				
				sendCommand(setNumber);
				checkState = parseMsg(">");
				
				if(debug) System.out.println("Typing ... ");
				
				if(checkState) {
					os.flush();
					os.print("TEST : SMS Banking Project ."+ctrlZ);
//					os.print("\r\n");
					is = myPort.getInputStream( );  
		        	if(debug) System.err.println("(Wait) Buffering Text ... ");
		        	Thread.sleep( SHORTDELAY );
		            byte[] readBuffer =  new byte[ MAX_CHARS ];
		           
		            int numbytes =is.read(readBuffer);
		            response = new String(readBuffer);
		            
					System.err.println(response);
				}
				else
				{
					System.out.println("Error Occured");
				}
				
				System.exit(0);
			}
		}catch(IOException e) {
			System.out.println("Exception Thrown : ");
			System.err.println(e.toString());
			
		}
		catch(InterruptedException e) {
			System.out.println("Interrupted Exception Thrown : ");
			System.err.println(e.toString());
		}
	}
	
	protected Boolean parseMsg(String expectText) {
		if(response.indexOf(expectText)> 0)
			return true;
		else 
			return false;
	}
	
	
	public static void main(String[] args) throws UnsupportedCommOperationException, IOException, InterruptedException {
		SerialSms serial = new SerialSms();
		serial.getAllPorts();
		serial.sendCommand("At +CMGR=30");
//		serial.sendCommand("AT+CMGL=\"REC UNREAD\"");
//		Thread t = new Thread(serial);
//		t.start();
        serial.expect("OK");
//		serial.sendMsg();
		is.close( );
        os.close( );
	    
	}
	
}
